/**
 * 向后端请求用户的菜单，动态生成路由
 */
import { constantRouterMap, asyncRouterMap, accountMap } from '@/config/router.config'
// import { generatorDynamicRouter } from '@/router/generator-routers'
import resetRouter from '@/router/reset'
import cloneDeep from 'lodash.clonedeep'

function hasPermission(roles, route) {
  return roles.some(role => role.url === route.name)
  // if (route.meta && route.meta.roles) {
  //   // return roles.some(role => route.meta.roles.includes(role))

  // } else {
  //   return false
  // }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, permissionsPLus) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(permissionsPLus, tmp) || tmp.follow) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissionsPLus)
      }
      res.push(tmp)
    }
  })
  return res
}

// 按钮权限
export function addBtnAction(roles, action){
  if(roles.permissions && roles.permissions.length !=0 ){
    roles.permissions.forEach(v=>{
      addBtnAction(v, action)
    })
  } else {
    let actionUrl = roles.url || ''
    actionUrl = actionUrl.substr(1,actionUrl.length).replaceAll('/','_')
    action.push(actionUrl || '')
  }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    rolsAction: []
    // addRouters: asyncRouterMap
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_ROLSACTION: (state, rolsAction) => {
      state.rolsAction = rolsAction
    },
    SET_ADDROUTERS: (state, addRouters) => {
      state.addRouters = addRouters
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        // 设置路由   比对
        let permissionsPLus = [], actionList = [];
        asyncRouterMap && asyncRouterMap.map(v => {
          addBtnAction(v, actionList)
          permissionsPLus.push(v)
          console.log(v)
          if (v.children && v.children.length !== 0) {
            v.children.map(it => {
              permissionsPLus.push(it)
            })
          }
        })

        let _asyncRouterMap = cloneDeep(asyncRouterMap)
        let accessedRoutes = filterAsyncRoutes(asyncRouterMap[0].children, permissionsPLus)
        _asyncRouterMap[0].children = [...accessedRoutes, ...asyncRouterMap[0].children]
        _asyncRouterMap.splice(1,0,accountMap[0])
        console.log(_asyncRouterMap);
        commit('SET_ROUTERS', _asyncRouterMap)
        commit('SET_ROLSACTION', actionList)
        resolve()
      })
    },
    reSetRoutes({ commit }, data){
      return new Promise((resolve,reject) => {
        commit('SET_ROUTERS', [])
        commit('SET_ROLSACTION', [])
        resolve()
      })
    }
  }
}

export default permission
